'use client';

import { useEffect } from 'react';
import mockApi from '@/lib/mock';

// Mock API接口类型定义
interface MockApi {
  init: () => void;
  setEnabled: (enabled: boolean) => void;
  exportData: () => any;
}

// 类型断言
const typedMockApi = mockApi as MockApi;

/**
 * Mock数据加载器组件
 * 用于在客户端环境中初始化Mock API
 * 只在开发环境中自动启用
 */
const MockLoader = () => {
  useEffect(() => {
    // 只在开发环境中自动初始化Mock
    if (process.env.NODE_ENV === 'development') {
      try {
        console.log('Initializing Mock API...');
        typedMockApi.init();
        console.log('Mock API initialized successfully');
      } catch (error) {
        console.error('Failed to initialize Mock API:', error);
      }
    } else {
      console.log('Mock API is disabled in production environment');
    }

    // 清理函数
    return () => {
      // 这里可以添加任何需要的清理逻辑
      console.log('MockLoader unmounted');
    };
  }, []);

  // 可以添加一个调试控制面板
  const DebugControls = () => {
    const toggleMock = (enabled: boolean) => {
      typedMockApi.setEnabled(enabled);
    };

    const exportData = () => {
      const data = typedMockApi.exportData();
      // 将数据下载为JSON文件
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `mock-data-${new Date().toISOString().slice(0, 10)}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      console.log('Mock data exported');
    };

    return (
      <div 
        className="fixed bottom-4 right-4 p-2 rounded-md bg-black bg-opacity-70 text-xs text-green-400 z-50"
        style={{ fontSize: '10px' }}
      >
        <div className="mb-1 font-mono">🔧 MOCK API</div>
        <div className="flex flex-col gap-1">
          <button 
            onClick={() => toggleMock(true)}
            className="px-2 py-1 bg-green-900 bg-opacity-50 hover:bg-opacity-70 rounded text-[9px]"
          >
            Enable
          </button>
          <button 
            onClick={() => toggleMock(false)}
            className="px-2 py-1 bg-red-900 bg-opacity-50 hover:bg-opacity-70 rounded text-[9px]"
          >
            Disable
          </button>
          <button 
            onClick={exportData}
            className="px-2 py-1 bg-blue-900 bg-opacity-50 hover:bg-opacity-70 rounded text-[9px]"
          >
            Export Data
          </button>
        </div>
      </div>
    );
  };

  // 只在开发环境显示调试控件
  return process.env.NODE_ENV === 'development' ? <DebugControls /> : null;
};

export default MockLoader;